<template>
  <t-card :bordered="false">
    <!-- <div class="top-right">
    <t-button theme="primary" @click="formRef?.submit" v-permission="['system:engineering-accounting-expenses:start-settlement-approval']" v-if="result == null || result == 3|| result == 4">
      提交审核
    </t-button>
    <span v-if="result" style="margin-left: var(--td-comp-margin-s)"
        ><t-tag :theme="getTagThemeAndLabel(result - 1).theme">{{
          getTagThemeAndLabel(result - 1).label
        }}</t-tag>
      </span>
    </div> -->
    <!-- 自定义表格 -->
    <!-- <t-form ref="formRef" :data="formData" reset-type="initial"> -->
    <t-table      
      row-key="index" 
      :data="tableData"  
      size="small"
      stripe 
      bordered 
      :columns="columns">
      <template #createTime="{ row, rowIndex }">
        {{ row.createTime?dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss'):'' }}
      </template>
      <template #operation="{ row }">
        <t-space break-line>
          <t-popconfirm content="确认放样该项吗？"
            v-if="!row.id"
            @confirm="handleConfirmComplete({ name:row.name ,stage: row.stage, orderId: orderId, })">
            <t-link theme="primary" v-permission="['system:lofting:create']" > 确认放样 </t-link>
          </t-popconfirm>
        </t-space>
      </template>
    </t-table>
  <!-- </t-form> -->


  </t-card>
   <!-- 粘性审批对话框 -->
   <sticky-approve-dialog ref="stickyApproveDialogRef22" :order-id="orderId" approve-type="22" />
</template>


<script setup lang="ts">
import dayjs from 'dayjs';
import { FormInstanceFunctions, MessagePlugin, SubmitContext, TableCol } from 'tdesign-vue-next';
import { computed, inject, onMounted, Ref, ref, useTemplateRef } from 'vue';

import CustomTable from '@/components/custom/table/index.vue';
import StickyApproveDialog from '@/pages/approve/components/sticky-approve-dialog .vue';

import { useDictionaryStore } from '@/store';
import { systemLoftingListCRUD } from '@/api/project/details';

interface TagThemeAndLabel {
  theme: 'warning' | 'success' | 'danger' | 'default';
  label: string;
}
// 定义 props
const props = defineProps({
  injectKey: {
    type: String,
    default: 'engineeringDetails',
  },
});
// 字典仓库
const dictionaryStore = useDictionaryStore();
// 默认的注入键
const injectKey = props.injectKey
// 动态注入数据
const details = inject<Ref<Record<string, any>>>(injectKey);
// 施工详情
const engineeringDetails = details;
const engineeringId = details.value.engineeringId || details.value.id
const orderId = details.value.orderId || details.value.id

  const formRef = useTemplateRef<FormInstanceFunctions>('formRef');
// columns
const columns: TableCol[] = [
  { colKey: 'name', title: '放样阶段' },
  { colKey: 'createTime', title: '放样时间' },
  { colKey: 'operation', title: '操作', fixed: 'right' },
].map(column => ({ ...column, align: 'center' }));
const result = ref()
const tableData = ref([])
// 添加表单数据
const formData = ref({ tableData: [] });
// 合同详情
const contractDetails = ref<Record<string, any>>({});
// 处理获取合同详情
const handleGetContractDetails = () => {
  const params = {
    orderId: orderId,
    // engineeringId: engineeringId,
  };
  systemLoftingListCRUD.page(params)
    .then((data) => {
      contractDetails.value = data.list;
      console.log(data)
      
      // 创建一个以 stageType 为键的映射，方便查找
      const stageMoneyMap: Record<string, number> = {};
      if(data?.total>0) {
        data.list.forEach((item:any) => {
          stageMoneyMap[item.stage] = item;
        });
        console.log(stageMoneyMap,'stageMoneyMap')
      }

      // 生成表格数据，并根据 stageType 填充对应的金额
      tableData.value = dictionaryStore.get('engineering_lofting').map((item, index) => {
        const existingRecord = stageMoneyMap[item.value];
        return {
          index, // 唯一标识
          name: item.label, // 放样阶段
          stage: item.value, // 放样阶段
          createTime: existingRecord?.createTime,
          id: existingRecord?.id,
        };
      });
      formData.value.tableData = tableData.value;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
onMounted(() => {
  handleGetContractDetails()
});
// 根据审批状态获取标签样式以及文字
const getTagThemeAndLabel = (result: number): TagThemeAndLabel => {
  const map: TagThemeAndLabel[] = [
    {
      theme: 'warning',
      label: '待审批',
    },
    {
      theme: 'success',
      label: '审批通过',
    },
    {
      theme: 'danger',
      label: '审批不通过',
    },
    {
      theme: 'danger',
      label: '审批已取消',
    },
  ];

  return result in map ? map[result] : { theme: 'default', label: '未知状态' };
};
// 处理确认完成
const handleConfirmComplete = (params: Record<string, any>) => {
  const { name, ...rest } = params;
  systemLoftingListCRUD.create({ ...rest })
    .then(() => {
      MessagePlugin.success(`${params.name}确认放样成功`);
      handleGetContractDetails()
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};


// 粘性审批对话框ref
const stickyApproveDialogRef22 = useTemplateRef('stickyApproveDialogRef22');
onMounted(() => {
  // const { approveType } = orderDetails.value;
  // stickyApproveDialogRef22.value.open();
});
</script>
